package com.ljl.yishu.net.communication;

import android.util.Log;
import com.ljl.yishu.net.RequestOBJ;
import com.ljl.yishu.net.ResponseOBJ;
import com.ljl.yishu.net.model.AddUserRequest;
import com.ljl.yishu.net.model.AddUserResponse;
import com.ljl.yishu.net.model.LoginRequest;
import com.ljl.yishu.net.model.LoginResponse;
import org.apache.log4j.Logger;
import org.springframework.http.*;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJacksonHttpMessageConverter;
import org.springframework.web.client.*;

import java.util.*;

public class Communication implements ProtalCommunicationI {

    private static String LOG = "Communication";

    private static int READTIMEOUT = 1000 * 10;
    private static int CONNECTTIMEOUT = 1000 * 5;
    private static Communication instance = null;
    private static String name;
    private static String handshakePassword;
    private static String URL = "http://192.168.2.106:8080/com-yaya-demo";

    private static final Logger log = Logger.getLogger(Communication.class);


    public void init(String base_url) {

        Communication.URL = base_url;
        Log.d(LOG, "init");
    }


    public static synchronized Communication getInstance() {

        if (instance == null) {

            instance = new Communication();

            Log.i(LOG, "call method getInstance -- new instace");
        }
        return instance;

    }


    public <R extends RequestOBJ, C extends ResponseOBJ> C getResult(
            String url, R request, Map<String, Object> formData,
            Class<C> responseClass, HttpMethod httpMethod) {

        HttpHeaders requestHeaders;

        // 单元测试时用
        // requestHeaders = dealRequestHeaders("2007010001",
        // "e1ab0912e726dc0cae683a55571e3d25fa3aa63b4f0c803e269c141b39540fbe");

        // 单元测试时注销
        requestHeaders = dealRequestHeaders(name, handshakePassword);

        HttpEntity<R> requestEntity = new HttpEntity<R>(request, requestHeaders);
        RestTemplate restTemplate = createRestTemplate();

        C result = null;
        ResponseEntity<C> responseEntity = null;

        try {
            if (formData == null) {
                responseEntity = restTemplate.exchange(url, httpMethod,
                        requestEntity, responseClass);
            } else {
                responseEntity = restTemplate.exchange(url, httpMethod,
                        requestEntity, responseClass, formData);
            }

            HttpStatus httpStatus = responseEntity.getStatusCode();
            System.out.println("###getReasonPhrase##  "
                    + httpStatus.getReasonPhrase());
            System.out.println("###name##  " + httpStatus.name());
            System.out.println("###toString##  " + httpStatus.toString());
            System.out.println("###value##  " + httpStatus.value());

            result = responseEntity.getBody();

        } catch (HttpClientErrorException e) {
            e.printStackTrace();

            System.out.println("###客户端异常###");

            try {
                result = responseClass.newInstance();
                result.kz10="400";
            } catch (IllegalAccessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } catch (HttpServerErrorException e) {
            e.printStackTrace();
            System.out.println("###服务器异常###");

            try {
                result = responseClass.newInstance();
                result.kz10="500";
            } catch (IllegalAccessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } catch (ResourceAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("###超时###");

            try {
                result = responseClass.newInstance();
                result.kz10="4";
            } catch (IllegalAccessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        } catch (RestClientException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("###未知异常###");

            try {
                result = responseClass.newInstance();
                result.kz10="600";
            } catch (IllegalAccessException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (InstantiationException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }
        System.out.println("##result.toString()#");
        // Log.d(LOG,
        // getTraceInfo() + "----result.toString()----"
        // + result.toString());
        return result;

    }


    private static RestTemplate createRestTemplate() {
        MappingJacksonHttpMessageConverter messageConverter = new MappingJacksonHttpMessageConverter();

        List<HttpMessageConverter<?>> messageConverters = new ArrayList<HttpMessageConverter<?>>();

        messageConverters.add(messageConverter);
        // Initialize a request factory, setting the request timeout
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setReadTimeout(READTIMEOUT);
        requestFactory.setConnectTimeout(CONNECTTIMEOUT);

        // Create a new RestTemplate instance

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setMessageConverters(messageConverters);
        restTemplate.setRequestFactory(requestFactory);
        return restTemplate;
    }


    private HttpHeaders dealRequestHeaders(String name, String token) {
        HttpHeaders requestHeaders = null;
//        if (name != null && token != null) {
//            requestHeaders = new HttpHeaders();
//            requestHeaders.setAccept(Collections.singletonList(new MediaType(
//                    "application", "json")));
//            requestHeaders.setContentType(new MediaType("application", "json"));
//            requestHeaders.add("name", name);
//            requestHeaders.add("handshakePassword", token);
//
//        }
        requestHeaders = new HttpHeaders();
        requestHeaders.setAccept(Collections.singletonList(new MediaType(
                "application", "json")));
        requestHeaders.setContentType(new MediaType("application", "json"));

//        requestHeaders.add("name", name);
       requestHeaders.add("sessionid", "11111111");
        return requestHeaders;

    }

    @Override
    public LoginResponse login(LoginRequest user) {

        String RequestURL = URL + "background/author/createuser";
        Map<String, Object> formData = new HashMap<String, Object>();
        getResult(RequestURL, user, formData, LoginResponse.class, HttpMethod.POST);
        return null;
    }

    @Override
    public AddUserResponse adduser(AddUserRequest user) {

        String RequestURL = URL + "/background/author/createuser";
        Map<String, Object> formData = new HashMap<String, Object>();
        formData.put("zh", user.zh);
        formData.put("mm", user.mm);
        formData.put("qq", user.qq);
        formData.put("sjh", user.sjh);
        AddUserResponse addUserResponse = getResult(RequestURL, user, formData, AddUserResponse.class, HttpMethod.POST);
        return addUserResponse;
    }
}
